###############################
### Quick Thematic Map      ###
###############################
rm(list = ls())

# fix input string errors
Sys.setlocale('LC_ALL', 'C')
options(scipen=20)

##create folder structure
mainDir <- "<INSERT PATH>/Replication_Files/Results/graphs/map_scad"

subDir <- "R_out"
if (file.exists(file.path(mainDir, subDir))){
  setwd(file.path(mainDir, subDir))
} else {
  dir.create(file.path(mainDir, subDir))
  setwd(file.path(mainDir, subDir))
}

# required
lop <- c("raster", "tmap","readstata13", "sf", "RColorBrewer", "tmaptools", "dplyr", "OpenStreetMap")
#lop <- c("raster", "foreign", , "rgdal", "rgeos", "doSNOW", "foreach", "doRNG", "doParallel", "spdep", "sp", "maptools", "reshape2", "expm")
newp <- lop[!(lop %in% installed.packages()[,"Package"])]
if(length(newp)) install.packages(newp)
lapply(lop, require, character.only = TRUE)

# devtools::install_github("mtennekes/tmap")
# require("tmap")

## set up font family
# install.packages("extrafont")
library(extrafont)
# font_import()
# y
loadfonts()
loadfonts(device="win")

palette_name <- "Set1"
legend_colors <- get_brewer_pal(palette_name, n=4)

## zone data
grid.sf <- st_read("../../../../../Data/country_regions/gadm1_clean.shp")

## data
dta <- read.dta13("../../../../../Data/Merge/IDA_Aid_GED_ADM1.dta")


### get sf object for entire African countries
africa_countries <- st_read("../../../../../Data/country_regions/gadm28_adm0.shp")
africa_countries <- subset(africa_countries, UNREGION2=="Africa")
# manually set Reunion as Island
africa_countries[which((africa_countries$NAME_ENGLI=="Reunion")), which(names(africa_countries)=="Islands")] <- 1 
africa_countries <- subset(africa_countries, Islands==0)
#add Madagscar and Mauritius to sample despite being islands
isos <- c(as.character(unique(africa_countries$ISO)), "MDG", "MUS")
africa_countries$ISO <- as.character(africa_countries$ISO)


## Get sf data
gadm1 <- st_read("../../../../../Data/country_regions/gadm1_clean.shp")
gadm1_africa <- gadm1 %>% 
  subset(., ISO%in%isos) 
gadm1_africa$ISO <- as.character(gadm1_africa$ISO)

###############################
###       SCAD Data
### Please download the SCAD Data from https://www.strausscenter.org/ccaps-research-areas/social-conflict/database/
###############################
## load raw aid data to plot as points

location.df <- read.csv("SCAD2017Africa_Final.csv", sep=";", stringsAsFactors=F)

# drop if Mauritania (only Island in sample)
location.df <- location.df[which(location.df$countryname!="Mauritania"),]
# convert coordiante strings into numerical
location.df$longitude <- as.numeric(gsub(",", ".", location.df$longitude))
location.df$latitude <- as.numeric(gsub(",", ".", location.df$latitude))
location_sub.df <- subset(location.df, locnum==1 | locnum==2 | locnum==3 | locnum==4 | locnum==5 | locnum==6)
location.sf <- st_as_sf(location_sub.df, coords = c("longitude", "latitude"))


# define type of violence
location.sf$violence_type <- NA
location.sf$violence_type[which(location.sf$etype==1 | location.sf$etype==2)] <- "Demonstration"
location.sf$violence_type[which(location.sf$etype==3 | location.sf$etype==4)] <- "Riots"
location.sf$violence_type[which(location.sf$etype==5 | location.sf$etype==6)] <- "Strikes"
location.sf$violence_type[which(location.sf$etype==7& (location.sf$ndeath==0 | location.sf$ndeath==-99 ))] <- "Repression"
location.sf <- subset(location.sf, !(is.na(location.sf$violence_type)))

# demo.sf <- subset(location.sf, violence_type=="Demonstration")
# riot.sf <- subset(location.sf, violence_type=="Riots")
# strike.sf <- subset(location.sf, violence_type=="Strikes")
# repress.sf <- subset(location.sf, violence_type=="Repression")

rest.sf <- subset(location.sf, violence_type=="Strikes" | violence_type=="Demonstration" | violence_type=="Riots")
repress.sf <- subset(location.sf, violence_type=="Repression")

legend_colors <- get_brewer_pal(palette_name, n=2)
legend_colors <- legend_colors[c(2,1)] # change order of vector

#maplayout="esri-topo"
maplayout="nps"
## load basemap data
# read OSM raster data
osm_afri <- read_osm(africa_countries, ext=1.1, type=maplayout)
plot_conf <- function(){
  print (
    #tm_shape(osm_afri,bbox = st_bbox(africa_countries)+c(-5,-5,5,5)) +
    tm_shape(osm_afri) +
      tm_rgb() +
      tm_shape(africa_countries)+
      tm_borders(lwd = 2)+
      tm_shape(gadm1_africa) +
      tm_borders(col = "grey40", alpha = 0.4) +
      # plot scaddata
      tm_shape(rest.sf, ext=1.1) +
        tm_dots(col=legend_colors[1], shape = 21, scale=4.5, border.col="black", border.lwd = 0.2) +
      tm_shape(repress.sf, ext=1.1) +
        tm_dots(col=legend_colors[2], shape = 21, scale=4.5, border.col="black", border.lwd = 0.2) +
      tm_add_legend(type = "symbol"
                    , shape = 21
                    , size=1.8
                    , col = legend_colors
                    , labels = c("Demonstration, \nRiots, Strikes", "Non-lethal \nGov. Repression")) +
      tm_scale_bar(size =1
                   , width = 0.2)+
      tm_layout(legend.show=T
                , asp=NA
                , panel.label.size=2
                , inner.margins=c(.00,.00, .00, .00)
                , legend.position = c("left", "0.03")
                , legend.text.size = 2.8
                , legend.title.size = 2.2
                , legend.height = 1
                , legend.stack="vertical"
                , fontfamily = "Helvetica"
                , frame = F #put frame around graph?
                , legend.outside = F # legend outside of margin?
                , outer.margins = c(0, 0, 0, 0) # Relative margins between device and frame (bottom, left, top, right)
      )
    
  )
}


plot_conf <- function(){
  print (
    #tm_shape(osm_afri,bbox = st_bbox(africa_countries)+c(-5,-5,5,5)) +
    tm_shape(osm_afri) +
      tm_rgb() +
      # plot scaddata
      tm_shape(rest.sf, ext=1.1) +
        tm_dots(col=legend_colors[1], shape = 21, scale=4.5, border.col="black", border.lwd = 0.2) +
      tm_shape(repress.sf, ext=1.1) +
        tm_dots(col=legend_colors[2], shape = 21, scale=4.5, border.col="black", border.lwd = 0.2) +
      tm_add_legend(type = "symbol"
                    , shape = 21
                    , size=1.8
                    , col = legend_colors
                    , labels = c("Demonstration, \nRiots, Strikes", "Non-lethal \nGov. Repression")) +
      tm_scale_bar(size =1
                   , width = 0.2)+
      tm_layout(legend.show=T
                , asp=NA
                , panel.label.size=2
                , inner.margins=c(.00,.00, .00, .00)
                , legend.position = c("left", "0.03")
                , legend.text.size = 2.8
                , legend.title.size = 2.2
                , legend.height = 1
                , legend.stack="vertical"
                , fontfamily = "Helvetica"
                , frame = F #put frame around graph?
                , legend.outside = F # legend outside of margin?
                , outer.margins = c(0, 0, 0, 0) # Relative margins between device and frame (bottom, left, top, right)
      )
    
  )
}



png(paste0("map_conf_scad.png"))
plot_conf()
dev.off()

pdf(paste0("map_conf_scad.pdf"), width=8, height=8)
par(mfrow=c(1,1))
par(mar = c(0,0,0,0)) # c(bottom, left, top, right)
plot_conf()
dev.off()